<?php

include_once dirname(__DIR__).'/third_party/phpcode_shield.php';		//加载防注入代码
class Ay extends CI_Controller 
{
	/*
		构造函数
	*/
	function __construct() {
		header('Content-Type: text/html; charset=utf-8'); 
		parent::__construct();
		$this->load->helper('url');
	}
	
	
	/*
		判断是否微信的
	*/
	public function is_weixin() { 
		if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ) {
				return true;
		}	

		return false;
	}
	

	private function getAccountIdByOpenid($open_id)
	{
		$request_ary['open_id'] = $open_id;
		$this->load->model('account/account_model','',true);
		$userinfo_result = $this->account_model->getUserInfo($request_ary);
		if(!isset($userinfo_result['data']['account_id']) || $userinfo_result['data']['account_id'] == "")
		{
			return -1;
		}
		$account_id = $userinfo_result['data']['account_id'];
		return $account_id;
	}

    private function getUserCodeByOpenid($open_id)
    {
        $request_ary['open_id'] = $open_id;
        $this->load->model('account/account_model','',true);
        $userinfo_result = $this->account_model->getUserInfo($request_ary);
        if(!isset($userinfo_result['data']['user_code']) || $userinfo_result['data']['user_code'] == "")
        {
            return -1;
        }
        $user_code = $userinfo_result['data']['user_code'];
        return $user_code;
    }
	
	/*
		提示在微信浏览器打开
	*/
	public function warmingWX() {

		$data['base_url'] = base_url();				
		$this->load->view("warming_wx",$data);
	}

    //本地设置测试账号
	private function testSetupOpenID() {
		return;
		
		if (isset($_GET['open_id'])) {
			$_SESSION['WxOpenID'] = $_GET['open_id'];
		} else {
			$_SESSION['WxOpenID'] = "oo0vEw6rHixmZZHTZ5lAniEd-coM";
		}
	}
	public function cz(){
        if(isset($_SESSION['WxOpenID'])) {
            $open_id = $_SESSION['WxOpenID'];
            $request_ary['open_id'] = $open_id;
            $this->load->model('account/account_model','',true);
            $userinfo_result = $this->account_model->getUserInfo($request_ary);

            if(!isset($userinfo_result['data']['account_id']) || $userinfo_result['data']['account_id'] == "")
            {
                $direct_url = base_url("y/ym");
                Header("Location:".$direct_url);
                return;
            }

            $request_ary['account_id'] =$userinfo_result['data']['account_id'];
            $this->load->model('flower/room_model','',true);
            $result = $this->room_model->getRoomTicket($request_ary);
            $data['base_url'] = base_url();
            $data['user'] = $userinfo_result['data'];
            $data['card'] = $result['data']['ticket_count'];
            $data['account_id'] = $userinfo_result['data']['account_id'];

            $data['image_url']= Game_Const::ImageUrl;
            $data['base_url'] = base_url();
            $data['showArr'] = Game_CONST::PayList;
            $this->load->view("chongzhi.php", $data);
        }else{
            $direct_url = base_url("y/ym");
            Header("Location:".$direct_url);
        }
    }
    public function chongzhi(){
        if(isset($_SESSION['WxOpenID'])) {
            $open_id = $_SESSION['WxOpenID'];
            $request_ary['open_id'] = $open_id;
            $this->load->model('account/account_model', '', true);
            $userinfo_result = $this->account_model->getUserInfo($request_ary);

            if (!isset($userinfo_result['data']['account_id']) || $userinfo_result['data']['account_id'] == "") {
                $direct_url = base_url("y/ym");
                Header("Location:" . $direct_url);
                return;
            }
            $account_id = $userinfo_result['data']['account_id'];
            $param = $_GET;
            //判断支付方式
            if ($param['pay_type'] == 'alipay_QR') {
                $pay_type = '0202';
            } else {
                $pay_type = '0201';
            }
            $payList = Game_CONST::PayList;
            $payData = $payList[$param['pay_data']];
            $timestamp = time();
            $transAmt = $payData['pay_amount'] * 100;
            $cardCount = $payData['count'];
            $requestNo = "R" . $timestamp . rand(100, 999);
            $outTradeNo = "O" . $timestamp . rand(100, 999);
            $post = [
                'requestNo' => $requestNo,
                'merNo' => '13030972',
                'transType' => '0200',
                'payWayCode' => $pay_type,
                'subMerNo' => ''
            ];
            $data = [
                'outTradeNo' => $outTradeNo,//订单号
                'transAmt' => $transAmt,//支付金额(分)
                'currency' => 'RMB',
                'subject' => '房卡' . $outTradeNo,
                'notifyUrl' => base_url() . "ay/chongzhi_notify",//异步回调地址
                'orderDate' => date('Ymd'),
                'clientIp' => '127.0.0.1',
                'returnUrl' => base_url() . "ay/chongzhi_return",//同步回调地址
            ];

            $post = $this->sign($post, $data);
            if ($result = $this->curl_post('http://47.52.154.185:8082/v1.0/payment', $post)) {
                if ($result['code'] != '0000') {
                    header("Location:" . base_url() . "ay/chongzhi_return?msg=" . $result['message'] . "&code=" . $result['code']);
                    exit();
                    //echo ['code' => 0, 'msg' => $result['message']];
                }
                $res = json_decode($result['data'], true);

                $dbData = [
                    'create_time' => $timestamp,
                    'account_id' => $account_id,
                    'transAmt' => $transAmt,
                    'cardCount' => $cardCount,// int(11) DEFAULT NULL COMMENT '房卡数量',
                    'status' => 0, //tinyint(4) DEFAULT NULL COMMENT '0:初始，1:成功，2:失败',
                    'outTradeNo' => $outTradeNo,// varchar(32) DEFAULT NULL COMMENT '购物订单号',
                    'payWayCode' => $pay_type,// varchar(32) DEFAULT NULL COMMENT '支付类型',
                    'requestNo' => $requestNo,// varchar(32) DEFAULT NULL COMMENT '请求单号',
                    //'bankOrderNo'=>100,// varchar(32) DEFAULT NULL COMMENT '后台订单号',
                    //'merFee'=>100,// decimal(10,0) DEFAULT '0' COMMENT '手续费',
                    //'orderNo'=>100,// varchar(32) DEFAULT NULL COMMENT '订单号',
                ];
                $this->load->model('account/account_model', '', true);
                $result = $this->account_model->chongzhiLog($dbData);

                echo $res['qrcode'];
                echo "<br><br><br><br><a href='" . $res['qrcode'] . "'>立即支付</a>";
                header("Location:" . $res['qrcode']);
                exit();
            } else {
                header("Location:" . base_url() . "ay/chongzhi_return?msg=接口错误&code=-1");
                exit();
            }

        }

    }
    public function chongzhi_return(){
        error_log("Return".file_get_contents('php://input', 'r').PHP_EOL,3,__DIR__."/../logs/pay.log");
        if (isset($_GET["code"])){
            echo $_GET["msg"];
            echo "<br><br><br><br><a href='".base_url()."f/ym"."'>返回首页</a>";
        }else{
            header("Location:".base_url(). "f/ym" );
        }
    }

    public function chongzhi_notify(){
        $this->load->model('account/account_model','',true);
        $input = file_get_contents('php://input', 'r');
        error_log("Notify:".$input.PHP_EOL,3,__DIR__."/../logs/pay.log");
//        $input = '{"code":"0000","data":"{\"bankOrderNo\":\"QE30O074880821951\",\"merFee\":\"3\",\"orderDate\":\"20190430\",\"orderNo\":\"15566074572141992\",\"outTradeNo\":\"O1556607457861\",\"paidTime\":\"1556607471000\",\"paySt\":2,\"subject\":\"房卡O1556607457861\",\"transAmt\":\"100\"}","merNo":"13030972","message":"操作成功","requestNo":"ad2377ccd8894c66b69c777d72f50bd4","signature":"64D78426BD9324ABAC713171364E3586","subMerNo":"120007141041","transType":"0200"}';
        $result = json_decode($input,true);
//echo "<pre>";
        if ($result && $result['code']='0000'){
            $data = json_decode($result['data'],true);
            $chongzhiData = $this->account_model->chongzhiData($data['outTradeNo']);
            //充值金额输入不符
            if ($chongzhiData['transAmt'] != $data['transAmt']){

            }

            $dbData = [
                'bankOrderNo'=>$data['bankOrderNo'],
                'merFee'=>$data['merFee'],
                'transAmt'=>$data['transAmt'],
                'orderNo'=>$data['orderNo'],
                'outTradeNo'=>$data['outTradeNo'],
                'status'=>1
            ];


            if ($chongzhiData['status'] != 1) {
                $result = $this->account_model->chongzhiUpdate($dbData);
                if ($result == DB_CONST::SUCCESS) {
                    $arrData = [
                        "account_id" => $chongzhiData['account_id'],
                        "count" => $chongzhiData['cardCount'],
                        "kf_id" => Game_CONST::PayAccount,
                    ];
                    $result = $this->chongzhi_action($arrData);
                }
            }

            echo "success";
        }

    }
    protected function chongzhi_action($request_array){
        //发送红包
        $rd_ary['account_id'] = $request_array['kf_id'];
        $rd_ary['ticket_count'] =  $request_array['count'];
        $rd_ary['content'] = "房卡充值发送";
        $this->load->model('activity/redenvelop_model','redenvelop_model',true);
        $rd_result = $this->redenvelop_model->createRedEnvelopOpt($rd_ary);
        if ($rd_result['result'] == OPT_CONST::FAILED){
            $result = json_encode($rd_result);
            echo $result;
            exit;
        }
//        var_dump($rd_result);
        error_log("Action-RD:".json_encode($rd_result).PHP_EOL,3,__DIR__."/../logs/pay.log");
        //接收红包
        $rs_ary['account_id'] = $request_array['account_id'];
        $rs_ary['recommend_code'] = -1;
        $rs_ary['code'] = $rd_result['data']['code'];
        $rs_result = $this->redenvelop_model->receiveRedEnvelopOpt($rs_ary);
//        $result = json_encode($rs_result);
//        var_dump($rs_result);
        error_log("Action-RS:".json_encode($rs_result).PHP_EOL,3,__DIR__."/../logs/pay.log");
        return $rs_result;
    }



    protected function sign($post,$data){
        //对data排序
        ksort($data);
//组合为转换斜杠的json
        $dataStr = '{';
        foreach ($data as $k1 => $v1) {
            if ($v1)
                $dataStr .= '"' . $k1 . '":"' . $v1 . '",';
        }
//去掉最后一个逗号
        $dataStr = rtrim($dataStr, ',');
        $dataStr .= '}';
//复制给公共参数
        $post['data'] = $dataStr;
//排序公共参数
        ksort($post);
        $str = '';
        foreach ($post as $k => $v) {
            if ($v)
                $str .= $k . '=' . $v . '&';
        }
// $str = rtrim($str, '&');
        $str .= 'xLRbbMz5oc2apYAQ';//商户秘钥
//md5签名并转换大写
        $post['signature'] = strtoupper(md5($str));

        return $post;
    }
    protected function curl_post($url, $data){
        $data_string = json_encode($data);
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS,$data_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Content-Length: ' . strlen($data_string)
        ));
        $result = curl_exec($ch);
        if (curl_errno($ch)) {
            print curl_error($ch);
        }
        curl_close($ch);
        return json_decode($result,true);

    }


	public function cRP() {
		$params = json_decode(file_get_contents('php://input'),true);
		
		if (
			isset($params['ticket_count'])&& 
			isset($params['content'])
			) {
			
			$open_id = $_SESSION['WxOpenID'];
			$account_id = $this->getAccountIdByOpenid($open_id);
			if($account_id <= 0)
			{
				show_404();	return;
			}
			
			if(isset($params['account_id']) && $params['account_id'] != $account_id)
			{
				$log_text = "function(createRedPackage):有人在偷刷红包啊啊啊啊啊啊！！！！！！！accountid:$account_id : ".json_encode($params)."  in file".__FILE__." on Line ".__LINE__;
				$this->load->model('error_model','',true);
				$this->error_model->writeLog($log_text);
				return;
			}

			$ticket_count = $params['ticket_count'];
			$content = $params['content'];

			$request_ary['account_id'] = $account_id;
			$request_ary['ticket_count'] = $ticket_count;
			$request_ary['content'] = $content;
			$this->load->model('activity/redenvelop_model','',true);
			$result = $this->redenvelop_model->createRedEnvelopOpt($request_ary);
			
			print_r(json_encode($result));
			
		} else {
			show_404();	
		}
	}


	//跳转到房卡红包view
	public function rp() {

		$is_weixin = $this->is_weixin();

		if (isset($_SESSION['WxOpenID'])) {
			$open_id = $_SESSION['WxOpenID'];
			
			$request_ary['open_id'] = $open_id;
			$this->load->model('account/account_model','',true);
			$userinfo_result = $this->account_model->getUserInfo($request_ary);
			if(!isset($userinfo_result['data']['account_id']) || $userinfo_result['data']['account_id'] == "")
			{
				$direct_url = base_url("y/yh");
				Header("Location:".$direct_url);
				return;
			}
			
			$request_ary['account_id'] =$userinfo_result['data']['account_id'];
			$this->load->model('flower/room_model','',true);
			$result = $this->room_model->getRoomTicket($request_ary);

			$this->load->model('dealer/dealer_model','',true);
			$dealerResult = $this->dealer_model->getDealerData($request_ary);

            $data['is_agent'] = '0';

			if (isset($dealerResult) && $dealerResult['result'] == 0) {
            	$data['is_agent'] = '1';
            	$data['dealer_screct'] = $dealerResult['data']['dealer_screct'];
			    $data['inventory_count'] = $dealerResult['data']['inventory_count'];
            }
		
			$data['base_url'] = base_url();
			
			$data['user'] = $userinfo_result['data'];
			$data['card'] = $result['data']['ticket_count'];

			$data['open_id'] = "";
			$data['account_id'] = $userinfo_result['data']['account_id'];

			$data['room_url'] =base_url("y/yh");

            $data['file_url'] = $data['base_url']; 
			$data['image_url']= Game_Const::ImageUrl; 

			$this->load->model('wechat_model','',true);
			$config_ary = $this->wechat_model->getWxConfig();
			$data['config_ary']=$config_ary;

            $this->load->view("roomRedPackage.php", $data);

		} else {
			$direct_url = base_url("y/yh");
			Header("Location:".$direct_url);
		}
	}

    //红包详情view
	public function rpD() {

		$is_weixin = $this->is_weixin();

		if (isset($_SESSION['WxOpenID']) && isset($_GET['red_code'])) {
			$open_id = $_SESSION['WxOpenID'];
			$red_code = $_GET['red_code'];

			$request_ary['open_id'] = $open_id;
			$request_ary['code'] = $red_code;

			$this->load->model('account/account_model','',true);
			$userinfo_result = $this->account_model->getUserInfo($request_ary);
			if(!isset($userinfo_result['data']['account_id']) || $userinfo_result['data']['account_id'] == "")
			{
				$direct_url = base_url("y/yh");
				Header("Location:".$direct_url);
				return;
			}
			
			$request_ary['account_id'] =$userinfo_result['data']['account_id'];
			$this->load->model('flower/room_model','',true);
			$result = $this->room_model->getRoomTicket($request_ary);

            $this->load->model('activity/redenvelop_model','',true);
			$redenvelop_result = $this->redenvelop_model->getRedEnvelopData($request_ary);
		
			$data['base_url'] = base_url();
			
			$data['user'] = $userinfo_result['data'];
			$data['card'] = $result['data']['ticket_count'];

			$data['open_id'] = "";
			$data['account_id'] = $userinfo_result['data']['account_id'];

			$data['red_package'] = $redenvelop_result['data'];
			$data['red_code'] = $red_code;

			$data['room_url'] =base_url("y/yh");
			$shareURL = "ay/rpD?red_code=".$red_code;
			//$data['share_url'] =  base_url($shareURL);

			$tcn['url_now'] =   base_url($shareURL);
			$tcn['url_long'] = $this->config->item("short_url").$tcn['url_now'];
			$data['share_url'] = $this->account_model->convertUrl($tcn);

			$data['share_icon'] = Game_Const::ImageUrl."files/images/redpackage/share_icon.jpg";

            $data['file_url'] = $data['base_url']; 
			$data['image_url']= Game_Const::ImageUrl; 
			
			$this->load->model('wechat_model','',true);
			$config_ary = $this->wechat_model->getWxConfig();
			$data['config_ary']=$config_ary;

			$this->load->view("redPackageDetail.php", $data);
		}
		else if(isset($_GET['red_code']))
		{
			$direct_url = base_url("y/re/".$_GET['red_code']);
			Header("Location:".$direct_url);
		}
		else {
			$direct_url = base_url("y/yh");
			Header("Location:".$direct_url);
		}
	}

	//领取红包
	public function receiveRP() {
		$params = json_decode(file_get_contents('php://input'),true);

		if (isset($params['red_code']) ) {
			$open_id = $_SESSION['WxOpenID'];
			$userinfo_result = $this->getUserInfoByOpenid($open_id);
			if($userinfo_result['data']['account_id'] <= 0)
			{
				show_404();	return;
			}
			$red_code = $params['red_code'];
			$request_ary['account_id'] = $userinfo_result['data']['account_id'];
			$request_ary['recommend_code'] = $userinfo_result['data']['recommend_code'];
			$request_ary['code'] = $red_code;
			$this->load->model('activity/redenvelop_model','',true);
			$result = $this->redenvelop_model->receiveRedEnvelopOpt($request_ary);

			print_r(json_encode($result));

		} else {
			show_404();
		}
	}

    //我的红包
	public function myRP() {
		$is_weixin = $this->is_weixin();
		if (isset($_SESSION['WxOpenID'])) {
			$open_id = $_SESSION['WxOpenID'];

			$request_ary['open_id'] = $open_id;
			$this->load->model('account/account_model','',true);
			$userinfo_result = $this->account_model->getUserInfo($request_ary);
			if(!isset($userinfo_result['data']['account_id']) || $userinfo_result['data']['account_id'] == "")
			{
				$direct_url = base_url("y/yh");
				Header("Location:".$direct_url);
				return;
			}
			
			$request_ary['account_id'] =$userinfo_result['data']['account_id'];
			$this->load->model('flower/room_model','',true);
			$result = $this->room_model->getRoomTicket($request_ary);
		
			$data['base_url'] = base_url();
			
			$data['user'] = $userinfo_result['data'];
			$data['card'] = $result['data']['ticket_count'];

			$data['open_id'] = "";
			$data['account_id'] = $userinfo_result['data']['account_id'];

			$data['room_url'] =base_url("y/yh");

            $data['file_url'] = $data['base_url']; 
			$data['image_url']= Game_Const::ImageUrl; 
			
			$this->load->model('wechat_model','',true);
			$config_ary = $this->wechat_model->getWxConfig();
			$data['config_ary']=$config_ary;

			$this->load->view("redPackageRecord.php", $data);
		} else {
            $dealer_num = 2;
			$direct_url = base_url("d/relist/".$dealer_num);
			Header("Location:".$direct_url);
		}
	}

    //我的团队
    public function myMT() {
        $is_weixin = $this->is_weixin();
        if (isset($_SESSION['WxOpenID'])) {
            $open_id = $_SESSION['WxOpenID'];

            $request_ary['open_id'] = $open_id;
            $this->load->model('account/account_model','',true);
            $userinfo_result = $this->account_model->getUserInfo($request_ary);
            if(!isset($userinfo_result['data']['account_id']) || $userinfo_result['data']['account_id'] == "")
            {
                $direct_url = base_url("y/yh");
                Header("Location:".$direct_url);
                return;
            }

            $request_ary['user_code'] = $userinfo_result['data']['user_code'];

            $data['base_url'] = base_url();

            $data['user'] = $userinfo_result['data'];


            $data['open_id'] = "";
            $data['account_id'] = $userinfo_result['data']['account_id'];

            $data['room_url'] =base_url("y/yh");

            $data['file_url'] = $data['base_url'];
            $data['image_url']= Game_Const::ImageUrl;

            $this->load->model('wechat_model','',true);
            $config_ary = $this->wechat_model->getWxConfig();
            $data['config_ary']=$config_ary;

            $this->load->view("myTeam.php", $data);
        } else {
            $dealer_num = 2;
            $direct_url = base_url("d/relist/".$dealer_num);
            Header("Location:".$direct_url);
        }
    }

    //获取我的团队记录/我推荐的代理
    public function sMT() {
        $params = json_decode(file_get_contents('php://input'),true);
        if (isset($params['page']) ) {
            $open_id = $_SESSION['WxOpenID'];
            $user_code = $this->getUserCodeByOpenid($open_id);
            if($user_code <= 0)
            {
                show_404();	return;
            }
            $request_ary['user_code'] = $user_code;
            $request_ary['page'] = $params['page'];
            $request_ary['dl'] = $params['dl'];//是否查代理
            $this->load->model('account/account_model','',true);
            $result = $this->account_model->getMyTeamList($request_ary);
            print_r(json_encode($result));
        } else {
            show_404();
        }
    }

    //获取发出红包的记录
	public function sRP() {
		$params = json_decode(file_get_contents('php://input'),true);
		
		if (isset($params['page']) ) {

			$open_id = $_SESSION['WxOpenID'];
			$account_id = $this->getAccountIdByOpenid($open_id);
			if($account_id <= 0)
			{
				show_404();	return;
			}

			$page = $params['page'];
			$request_ary['account_id'] = $account_id;
			$request_ary['page'] = $page;
			$this->load->model('activity/redenvelop_model','',true);
			$result = $this->redenvelop_model->getSendRedList($request_ary);
            
			print_r(json_encode($result));
			
		} else { 
			show_404();
		}	
	}

    //获取收取的红包记录
	public function rRP() {
		$params = json_decode(file_get_contents('php://input'),true);

		if (isset($params['page']) ) {
			
			$open_id = $_SESSION['WxOpenID'];
			$account_id = $this->getAccountIdByOpenid($open_id);
			if($account_id <= 0)
			{
				show_404();	return;
			}

			$page = $params['page'];
			$request_ary['account_id'] = $account_id;
			$request_ary['page'] = $page;
			$this->load->model('activity/redenvelop_model','',true);
			$result = $this->redenvelop_model->getReceiveRedList($request_ary);
            
			print_r(json_encode($result));
			
		} else { 
			show_404();
		}
	}


//********************* 分界线 ***********************
	private function getUserInfoByOpenid($open_id)
	{
		$request_ary['open_id'] = $open_id;
		$this->load->model('account/account_model','',true);
		$userinfo_result = $this->account_model->getUserInfo($request_ary);
		if(!isset($userinfo_result['data']['account_id']) || $userinfo_result['data']['account_id'] == "")
		{
			return -1;
		}
		return $userinfo_result;
	}

	public function slotmachine () {

		//$this->testSetupOpenID();

		$is_weixin = $this->is_weixin();

        //判断代理商编号是否存在
		if(!isset($_GET['dealer_num']))
		{
			log_message('error', "function(slotmachine):lack of dealer_num:"." in file".__FILE__." on Line ".__LINE__);
			show_404();exit;
		}

		$dealer_num = filter_var($_GET['dealer_num']);
		$DelaerConst = "Dealer_".$dealer_num;
		if(!class_exists($DelaerConst))
		{
			log_message('error', "function(slotmachine):dealer not exist:".$dealer_num." in file".__FILE__." on Line ".__LINE__);
			show_404();exit;
		}

		if (isset($_SESSION['WxOpenID'])) {
			$open_id = $_SESSION['WxOpenID'];

			$request_ary['open_id'] = $open_id;
			$request_ary['dealer_num'] = $dealer_num;
			$this->load->model('account/account_model','',true);
			$userinfo_result = $this->account_model->getUserInfo($request_ary);
			if(!isset($userinfo_result['data']['account_id']) || $userinfo_result['data']['account_id'] == "")
			{
				$direct_url = base_url("d/slot/".$dealer_num);
				Header("Location:".$direct_url);
				return;
			}
			
			$request_ary['account_id'] =$userinfo_result['data']['account_id'];
			$this->load->model('flower/room_model','',true);
			$result = $this->room_model->getRoomTicket($request_ary);
		
			$data['base_url'] = base_url();
			
			$data['socket'] = $DelaerConst::WebSocket_Host;
			$data['user'] = $userinfo_result['data'];
			$data['card'] = $result['data']['ticket_count'];

			$data['open_id'] = "";
			$data['account_id'] = $userinfo_result['data']['account_id'];

			$data['room_url'] =base_url("d/home");
			$data['share_url'] =  base_url("d/slot");
			$data['share_icon'] = base_url("files/images/tiger/home.jpg");
			$data['dealer_num'] = $dealer_num;
			
			$this->load->model('wechat_model','',true);
			$config_ary = $this->wechat_model->getWxConfig($dealer_num);
			$data['config_ary']=$config_ary;

			$this->load->view("d_".$dealer_num."/slotmachine.php", $data);
		} else {
			$direct_url = base_url("d/slot/".$dealer_num);
			Header("Location:".$direct_url);
		}
	}

	public function getSlotResult () {
		$params = json_decode(file_get_contents('php://input'),true);
        
		if (isset($_SESSION['WxOpenID']) && isset($params['bet_array']) && isset($params['dealer_num'])) {
			$openID = $_SESSION['WxOpenID'];
		    $bets = $params['bet_array'];
		    $dealer_num = $params['dealer_num'];

			$request_ary['open_id'] = $openID;
			$request_ary['bet_array'] = $bets;
			$request_ary['dealer_num'] = $dealer_num;

			$this->load->model('activity/slotmachine_model','',true);
			$result = $this->slotmachine_model->slotMachineOpt($request_ary);
            
			print_r(json_encode($result));
			
		} else { 
			show_404();
		}
	}


	public function homeSign() {

		//$this->testSetupOpenID();

		$is_weixin = $this->is_weixin();

        //判断代理商编号是否存在
		if(!isset($_GET['dealer_num']))
		{
			log_message('error', "function(homeSign):lack of dealer_num:"." in file".__FILE__." on Line ".__LINE__);
			show_404();exit;
		}

		$dealer_num = filter_var($_GET['dealer_num']);
		$DelaerConst = "Dealer_".$dealer_num;
		if(!class_exists($DelaerConst))
		{
			log_message('error', "function(homeSign):dealer not exist:".$dealer_num." in file".__FILE__." on Line ".__LINE__);
			show_404();exit;
		}
        
		if (isset($_SESSION['WxOpenID'])) {
			$open_id = $_SESSION['WxOpenID'];

			$request_ary['open_id'] = $open_id;
			$request_ary['dealer_num'] = $dealer_num;
			$this->load->model('account/account_model','',true);
			$userinfo_result = $this->account_model->getUserInfo($request_ary);
			if(!isset($userinfo_result['data']['account_id']) || $userinfo_result['data']['account_id'] == "")
			{
				$direct_url = base_url("d/sign/".$dealer_num);
				Header("Location:".$direct_url);
				return;
			}
			
			$request_ary['account_id'] =$userinfo_result['data']['account_id'];
			$this->load->model('flower/room_model','',true);
			$result = $this->room_model->getRoomTicket($request_ary);

			$data['base_url'] = base_url();
			
			$data['socket'] = $DelaerConst::WebSocket_Host;
			$data['user'] = $userinfo_result['data'];
			$data['card'] = $result['data']['ticket_count'];

			$data['open_id'] = "";
			$data['account_id'] = $userinfo_result['data']['account_id'];

			$data['room_url'] =base_url("d/home/".$dealer_num);
			$data['share_url'] =  base_url("d/sign/".$dealer_num);
			$data['share_icon'] = base_url("files/images/game/home.jpg");
			$data['dealer_num'] = $dealer_num;
			
			$this->load->model('wechat_model','',true);
			$config_ary = $this->wechat_model->getWxConfig($dealer_num);
			$data['config_ary']=$config_ary;

			$this->load->view("d_".$dealer_num."/homeSign.php", $data);
		} else {
			$direct_url = base_url("d/sign/".$dealer_num);
			Header("Location:".$direct_url);
		}
	}

	public function getSignList () {
		$params = json_decode(file_get_contents('php://input'),true);

		if (isset($params['account_id']) && isset($params['dealer_num'])) {
			$accountID = $params['account_id'];
		    $dealer_num = $params['dealer_num'];

			$request_ary['account_id'] = $accountID;
			$request_ary['dealer_num'] = $dealer_num;

			$this->load->model('activity/sign_model','',true);
			$result = $this->sign_model->getSignList($request_ary);
            
			print_r(json_encode($result));
			
		} else { 
			show_404();
		}
	}

	public function signIn () {
		$params = json_decode(file_get_contents('php://input'),true);

		if (isset($params['account_id']) && isset($params['dealer_num'])) {
			$accountID = $params['account_id'];
		    $dealer_num = $params['dealer_num'];

			$request_ary['account_id'] = $accountID;
			$request_ary['dealer_num'] = $dealer_num;

			$this->load->model('activity/sign_model','',true);
			$result = $this->sign_model->signInOpt($request_ary);
            
			print_r(json_encode($result));
			
		} else { 
			show_404();
		}
	}

	public function getGameScore () {
		$params = json_decode(file_get_contents('php://input'),true);
	
		if (isset($params['account_id']) && isset($params['from']) && isset($params['to']) && isset($params['dealer_num'])) {
			$request_ary['account_id'] = $params['account_id'];
		    $request_ary['from'] = $params['from'];
		    $request_ary['to'] = $params['to'];
		    $request_ary['dealer_num'] = $params['dealer_num'];

			$this->load->model('account/account_model','',true);
		    $result = $this->account_model->getScoreStatistics($request_ary);
            
			print_r(json_encode($result));
			
		} else { 
			show_404();
		}
	}

	//代理商红包
	public function agentRedPackage() {

		//$this->testSetupOpenID();

		$is_weixin = $this->is_weixin();
     
		//判断代理商编号是否存在
		if(!isset($_GET['dealer_num']))
		{
			log_message('error', "function(agentRedPackage):lack of dealer_num:"." in file".__FILE__." on Line ".__LINE__);
			show_404();exit;
		}

		$dealer_num = filter_var($_GET['dealer_num']);
		$DelaerConst = "Dealer_".$dealer_num;
		if(!class_exists($DelaerConst))
		{
			log_message('error', "function(agentRedPackage):dealer not exist:".$dealer_num." in file".__FILE__." on Line ".__LINE__);
			show_404();exit;
		}

		if (isset($_SESSION['WxOpenID'])) {
			$open_id = $_SESSION['WxOpenID'];

			$request_ary['dealer_num'] = $dealer_num;
			$request_ary['open_id'] = $open_id;

			$this->load->model('account/account_model','',true);
			$userinfo_result = $this->account_model->getUserInfo($request_ary);
			if(!isset($userinfo_result['data']['account_id']) || $userinfo_result['data']['account_id'] == "")
			{
				$direct_url = base_url("d/relist/".$dealer_num);
				Header("Location:".$direct_url);
				return;
			}
			
			$request_ary['account_id'] =$userinfo_result['data']['account_id'];
			$this->load->model('flower/room_model','',true);
			$result = $this->room_model->getRoomTicket($request_ary);
		
			$data['base_url'] = base_url();
			
			$data['socket'] = $DelaerConst::WebSocket_Host;
			$data['user'] = $userinfo_result['data'];
			$data['card'] = $result['data']['ticket_count'];

			$data['open_id'] = "";
			$data['account_id'] = $userinfo_result['data']['account_id'];

			$data['room_url'] =base_url("d/home/".$dealer_num);
			$data['dealer_num'] = $dealer_num;
			
			$this->load->model('wechat_model','',true);
			$config_ary = $this->wechat_model->getWxConfig($dealer_num);
			$data['config_ary']=$config_ary;

			$this->load->view("d_".$dealer_num."/agentRedPackageRecord.php", $data);
		} else {
			$direct_url = base_url("d/relist/".$dealer_num);
			Header("Location:".$direct_url);
		}
	}

	//代理商红包详情v
	public function agentRedPackageDetail() {

		//$this->testSetupOpenID();

		$is_weixin = $this->is_weixin();

		//判断代理商编号是否存在
		if(!isset($_GET['dealer_num']))
		{
			log_message('error', "function(agentRedPackageDetail):lack of dealer_num:"." in file".__FILE__." on Line ".__LINE__);
			show_404();exit;
		}

		$dealer_num = filter_var($_GET['dealer_num']);
		$DelaerConst = "Dealer_".$dealer_num;
		if(!class_exists($DelaerConst))
		{
			log_message('error', "function(agentRedPackageDetail):dealer not exist:".$dealer_num." in file".__FILE__." on Line ".__LINE__);
			show_404();exit;
		}

		if (isset($_SESSION['WxOpenID']) && isset($_GET['red_code'])) {
			$open_id = $_SESSION['WxOpenID'];
			$red_code = $_GET['red_code'];

			$request_ary['dealer_num'] = $dealer_num;
			$request_ary['open_id'] = $open_id;
			$request_ary['code'] = $red_code;

			$this->load->model('account/account_model','',true);
			$userinfo_result = $this->account_model->getUserInfo($request_ary);
			if(!isset($userinfo_result['data']['account_id']) || $userinfo_result['data']['account_id'] == "")
			{
				$direct_url = base_url("d/re/".$dealer_num."/".$_GET['red_code']);
				Header("Location:".$direct_url);
				return;
			}
			
			
			$request_ary['account_id'] =$userinfo_result['data']['account_id'];
			$this->load->model('flower/room_model','',true);
			$result = $this->room_model->getRoomTicket($request_ary);

            $this->load->model('activity/redenvelop_model','',true);
			$redenvelop_result = $this->redenvelop_model->getRedEnvelopData($request_ary);
		
			$data['base_url'] = base_url();
			
			$data['socket'] = $DelaerConst::WebSocket_Host;
			$data['user'] = $userinfo_result['data'];
			$data['card'] = $result['data']['ticket_count'];

			$data['open_id'] = "";
			$data['account_id'] = $userinfo_result['data']['account_id'];

			$data['red_package'] = $redenvelop_result['data'];
			$data['red_code'] = $red_code;

			$data['room_url'] =base_url("d/home/".$dealer_num);
			$shareURL = "d/re/".$dealer_num."/".$red_code;
			$data['share_url'] =  base_url($shareURL);
			$data['share_icon'] = base_url("files/images/redpackage/share_icon.jpg");
			$data['dealer_num'] = $dealer_num;
			
			$this->load->model('wechat_model','',true);
			$config_ary = $this->wechat_model->getWxConfig($dealer_num);
			$data['config_ary']=$config_ary;

			$this->load->view("d_".$dealer_num."/agentRedPackageDetail.php", $data);
		}
		else if(isset($_GET['red_code']))
		{
			$direct_url = base_url("d/re/".$dealer_num."/".$_GET['red_code']);
			Header("Location:".$direct_url);
		}
		 else {
			$direct_url = base_url("d/relist/".$dealer_num);
			Header("Location:".$direct_url);
		}
	}

	public function createAgentRedPackage() {
		$params = json_decode(file_get_contents('php://input'),true);
		
		if ( 
			isset($params['ticket_count']) && 
			isset($params['content']) && 
			isset($params['dealer_num']) && 
			isset($params['dealer_screct'])) {

			$open_id = $_SESSION['WxOpenID'];
			$dealer_num = $params['dealer_num'];
			$account_id = $this->getAccountIdByOpenid($dealer_num,$open_id);
			if($account_id <= 0)
			{
				show_404();	return;
			}

			//$account_id = $params['account_id'];
			$ticket_count = $params['ticket_count'];
			$content = $params['content'];
			$dealer_num = $params['dealer_num'];
			$dealer_screct = $params['dealer_screct'];

			$request_ary['dealer_num'] = $dealer_num;
			$request_ary['account_id'] = $account_id;
			$request_ary['ticket_count'] = $ticket_count;
			$request_ary['content'] = $content;
			$request_ary['dealer_screct'] = $dealer_screct;
			$this->load->model('dealer/dealer_model','',true);
			$result = $this->dealer_model->createRedEnvelopOpt($request_ary);
			
			print_r(json_encode($result));
			
		} else {
			show_404();	
		}
	}

	//获取代理商发出红包的记录
	public function getAgentOutRedPackage() {
		$params = json_decode(file_get_contents('php://input'),true);
		
		if (
			isset($params['page']) && 
			isset($params['dealer_num'])) {

			$open_id = $_SESSION['WxOpenID'];
			$dealer_num = $params['dealer_num'];
			$account_id = $this->getAccountIdByOpenid($dealer_num,$open_id);
			if($account_id <= 0)
			{
				show_404();	return;
			}
			
			//$account_id = $params['account_id'];
			$page = $params['page'];
			$dealer_num = $params['dealer_num'];

			$request_ary['dealer_num'] = $dealer_num;
			$request_ary['account_id'] = $account_id;
			$request_ary['page'] = $page;
			$this->load->model('dealer/dealer_model','',true);
			$result = $this->dealer_model->getRedEnvelopList($request_ary);
            
			print_r(json_encode($result));
			
		} else { 
			show_404();
		}	
	}

    //查询最近房间成绩数据
    public function rSo() {
        $params = json_decode(file_get_contents('php://input'),true);

        if (isset($params['page']) ) {
            $open_id = $_SESSION['WxOpenID'];
            $account_id = $this->getAccountIdByOpenid($open_id);
            if($account_id <= 0)
            {
                show_404();	return;
            }
            $request_ary['account_id'] = $account_id;
            $request_ary['page'] = $params['page'];
            $request_ary['rows'] = $params['rows'];
            $request_ary['game_type'] = $params['game_type'];
            $this->load->model('account/account_model','',true);

            $result = $this->account_model->getGameScore($request_ary);
            print_r(json_encode($result));
        } else {
            show_404();
        }
    }

	//查询最近开房记录
	public function mR() {
		$params = json_decode(file_get_contents('php://input'),true);

		if (isset($params['page']) ) {
			$open_id = $_SESSION['WxOpenID'];
			$account_id = $this->getAccountIdByOpenid($open_id);
			if($account_id <= 0)
			{
				show_404();	return;
			}
			$request_ary['account_id'] = $account_id;
			$request_ary['page'] = $params['page'];
			$request_ary['rows'] = $params['rows'];
			$request_ary['game_type'] = $params['game_type'];
			$this->load->model('account/account_model','',true);
			$result = $this->account_model->getMyRoom($request_ary);
			print_r(json_encode($result));
		} else {
			show_404();
		}
	}

    //我的房间战绩页面
    public function myMroom() {
        $this->is_weixin();
        $roomId = $_GET['roomId'];
        $gameType = $_GET['gameType'];
		$roomNumber = $_GET['roomNumber'];
        if (isset($_SESSION['WxOpenID']) && isset($roomId) && isset($gameType)) {
            $data['base_url'] = base_url();
            $data['roomId'] = $roomId;
            $data['gameType'] = $gameType;
			$data['roomNumber'] = $roomNumber;
            $data['image_url']= Game_Const::ImageUrl;
            $this->load->view("myRoomScore.php", $data);
        } else {
            $dealer_num = 2;
            $direct_url = base_url("d/relist/".$dealer_num);
            Header("Location:".$direct_url);
        }
    }

	//房主
	public function fzRoom() {
		$this->is_weixin();
		$roomId = $_GET['roomId'];
		$gameType = $_GET['gameType'];
		$roomNumber = $_GET['roomNumber'];
		if (isset($_SESSION['WxOpenID']) && isset($roomId) && isset($gameType) && isset($roomNumber)) {
			$data['base_url'] = base_url();
			$data['roomId'] = $roomId;
			$data['gameType'] = $gameType;
			$data['roomNumber'] = $roomNumber;
			$data['image_url']= Game_Const::ImageUrl;
			$data['is_close']= $_GET['is_close'];
			$data['max_count']= $_GET['max_count'];
			$this->load->view("fzRoomScore.php", $data);
		} else {
			$dealer_num = 2;
			$direct_url = base_url("d/relist/".$dealer_num);
			Header("Location:".$direct_url);
		}
	}

    //查询最近房间成绩数据
    public function roI() {
        $params = json_decode(file_get_contents('php://input'),true);
        if (isset($params['roomId']) && isset($params['gameType'])) {
            $open_id = $_SESSION['WxOpenID'];
            $account_id = $this->getAccountIdByOpenid($open_id);
            if($account_id <= 0)
            {
                show_404();	return;
            }
            $request_ary['roomId'] = $params['roomId'];
            $request_ary['gameType'] = $params['gameType'];
            $this->load->model('account/account_model','',true);
            $roomInfo = $this->account_model->getRoomInfo($request_ary);
            print_r(json_encode($roomInfo));
        } else {
            show_404();
        }
    }

	//房主查询最近房间成绩数据
	public function roFz() {
		$params = json_decode(file_get_contents('php://input'),true);
		if (isset($params['roomId']) && isset($params['gameType'])) {
			$open_id = $_SESSION['WxOpenID'];
			$account_id = $this->getAccountIdByOpenid($open_id);
			if($account_id <= 0)
			{
				show_404();	return;
			}
			$request_ary['roomId'] = $params['roomId'];
			$request_ary['gameType'] = $params['gameType'];
			$this->load->model('account/account_model','',true);
			$roomInfo = $this->account_model->getGameRoomInfo($request_ary);
			print_r(json_encode($roomInfo));
		} else {
			show_404();
		}
	}

    //跳转游戏战绩页面
    public function gmSc() {
        $is_weixin = $this->is_weixin();
        if (isset($_SESSION['WxOpenID'])) {
            $data['base_url'] = base_url();
            $data['image_url']= Game_Const::ImageUrl;
            $this->load->view("gameScore.php", $data);
        } else {
            $dealer_num = 2;
            $direct_url = base_url("d/relist/".$dealer_num);
            Header("Location:".$direct_url);
        }
    }

	//跳转游戏开房记录页面
	public function myMR() {
		$params = json_decode(file_get_contents('php://input'),true);
		$is_weixin = $this->is_weixin();
		if (isset($_SESSION['WxOpenID'])) {
			$data['base_url'] = base_url();
			$data['image_url']= Game_Const::ImageUrl;
			$this->load->view("gameRoom.php", $data);
		} else {
			$dealer_num = 2;
			$direct_url = base_url("d/relist/".$dealer_num);
			Header("Location:".$direct_url);
		}
	}


	//自定义防伪码
	public function updateMyCode() {
		$params = json_decode(file_get_contents('php://input'),true);
		if (isset($params['my_code']) ) {
			$open_id = $_SESSION['WxOpenID'];
			$account_id = $this->getAccountIdByOpenid($open_id);
			if($account_id <= 0)
			{
				show_404();	return;
			}
			$my_code = $params['my_code'];
			$request_ary['account_id'] = $account_id;
			$request_ary['my_code'] = addslashes($my_code);

			$this->load->model('account/account_model','',true);
			$result = $this->account_model->updateMyCode($request_ary);

			print_r(json_encode($result));
		} else {
			show_404();	
		}
	}




}
